package org.trackcore.dispatcher;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.trackcore.handler.DataHandler;
import org.trackcore.model.entity.BaseLog;
import org.trackcore.service.BaseLogService;
import org.trackcore.utils.DataUtils;
import org.trackcore.utils.ValidateUtils;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MonitorDataDispatcher {

    @Autowired
    private BaseLogService baseLogService;

    // 改用List注入
    @Autowired
    private List<DataHandler> handlerList;

    // 本地缓存处理器映射
    private Map<String, DataHandler> handlerMap;

    @PostConstruct
    public void initHandlerMap() {
        handlerMap = handlerList.stream()
                .collect(Collectors.toMap(
                        DataHandler::getHandlerKey,
                        handler -> handler
                ));
    }

    public void dispatch(Map<String, Object> rawData) {
        // 1. 基础校验
        ValidateUtils.checkRequiredFields(rawData, "id", "timestamp");
        // 2. 保存基础日志
        BaseLog baseLog = baseLogService.saveBaseLog(rawData);

        // 3. 处理监控数据
        List<Map<String, Object>> dataItems = DataUtils.getList(rawData, "data");
        dataItems.forEach(item -> {
            String handlerKey = DataUtils.getHandlerKey(item);
            DataHandler handler = handlerMap.get(handlerKey);
            if (handler != null) {
                handler.handle(item, baseLog.getId());
            }
        });
    }
}
